/*请求方法的别名：
 axios.request(config)
 axios.get(url[, config])
 axios.delete(url[, config])
 axios.head(url[, config])
 axios.post(url[, data[, config]])
 axios.put(url[, data[, config]])
 axios.patch(url[, data[, config]])
 标注： 在使用别名方法时， url、method、data 这些属性都不必在配置中指定。

 处理并发请求的助手函数：
 axios.all(iterable)
 axios.spread(callback)
 */
import Axios from "axios";
import {Message} from "element-ui";
import Constants from "common/constants";
import router from "basic/router";
import storeUtils from "utils/StoreUtils";

// 配置Axios默认值(后端配置跨域设置后此处不用配置)
const http = Axios.create({
	baseURL: Constants.base.baseURL,
	timeout: 1000,//响应时间
	headers: {
		// "Access-Control-Allow-Origin": "*",//解决cors头问题
		// "Access-Control-Allow-Headers": "Origin, Authorization, X-Requested-With, Content-Type, Accept",//解决session问题
		// "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
		"Content-Type": "application/json;charset=UTF-8" //配置请求头
	}
});

const clearToken = () => {
	// 清除token信息并跳转到登录页面,并携带当前页面的路径,在登录成功后返回当前页面，
	storeUtils.setSessionStore("token", null);
	router.replace({
		name: "/",
		params: {redirect: router.currentRoute.fullPath}
	});
};

//POST传参序列化(添加请求拦截器)
http.interceptors.request.use(
	(config) => {
		// 判断是否存在token，如果存在的话，则每个http header都加上token
		if (storeUtils.getSessionStore("token")) {
			config.headers.Authorization = `${storeUtils.getSessionStore("token")}`;
		}
		if (config.method === "post" && typeof (config.data) == "string") {
			config.data = JSON.parse(config.data);
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

//返回状态判断(添加响应拦截器)
http.interceptors.response.use(
	(response) => {
		if (!response.data.success) {
			return Promise.reject(response);
		}
		return response;
	},
	(error) => {
		if (error.response) {
			switch (error.response.status) {
				case 401:// 401: 未登录,未登录则跳转登录页面，并携带当前页面的路径,在登录成功后返回当前页面，这一步需要在登录页操作。
					clearToken();// 清除token
					break;
				// 403 token过期,登录过期对用户进行提示,清除本地token和清空vuex中token对象,跳转登录页面
				case 403:
					clearToken();// 清除token
					break;
				// 404请求不存在
				case 404:
					break;
				// 其他错误，直接抛出错误提示
				default:
					return Message.error(error.message);
			}
		} else {
			return Message.error(error.message);
		}
		return Promise.reject(error.response);   // 返回接口返回的错误信息
	}
);

//返回一个Promise(发送post请求)
http.fetchPost = (url, params, success, fail) => {
	return new Promise((resolve, reject) => {
		http.post(url, params)
		    .then(
			    (response) => {
				    resolve(response.data);
			    },
			    (error) => {
				    reject(error);
			    })
		    .catch((error) => {
			    reject(error);
		    });
	}).then(
		(response) => {
			if (success && typeof success === "function") {
				if (response && response.status === 200 && response.success) {
					success(response);
				}
			} else {
				return response;
			}
		},
		(error) => {
			if (fail && typeof fail === "function") {
				fail(error);
			}
			Message.error(error.data.message);
		}
	);
};
//返回一个Promise(发送get带参请求)
http.fetchGetParams = (url, params, success, fail) => {
	return new Promise((resolve, reject) => {
		http.get(url, {params: params})
		    .then(
			    (response) => {
				    resolve(response.data);
			    },
			    (error) => {
				    reject(error);
			    })
		    .catch((error) => {
			    reject(error);
		    });
	}).then(
		(response) => {
			if (success && typeof success === "function") {
				if (response && response.status === 200 && response.success) {
					success(response);
				}
			} else {
				return response;
			}
		},
		(error) => {
			if (fail && typeof fail === "function") {
				fail(error);
			}
			Message.error(error.data.message);
		}
	);
};
//返回一个Promise(发送get无参请求)
http.fetchGet = (url, success, fail) => {
	return new Promise((resolve, reject) => {
		http.get(url)
		    .then(
			    (response) => {
				    resolve(response.data);
			    },
			    (error) => {
				    reject(error);
			    })
		    .catch((error) => {
			    reject(error);
		    });
	}).then(
		(response) => {
			if (success && typeof success === "function") {
				if (response && response.status === 200 && response.success) {
					success(response);
				}
			} else {
				return response;
			}
		},
		(error) => {
			if (fail && typeof fail === "function") {
				fail(error);
			}
			Message.error(error.data.message);
		}
	);
};

export default http;
